package com.chint.largeData.views;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.webkit.GeolocationPermissions.Callback;
import android.webkit.JsResult;
import android.webkit.WebBackForwardList;
import android.webkit.WebSettings;
import android.webkit.WebStorage.QuotaUpdater;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class ProgressWebView extends WebView {

    //private ProgressBar progressbar;
    private Context ct;
    private int type;

    //private ThePreferentialBenefit benefit;
    public ProgressWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
        ct = context;
        initWebView(context);

    }

    //    @override
//    public void onFormResubmission(WebView view, Message dontResend, Message resend)   
//    {   
//        resend.sendToTarget();  
//     }  
   
    @SuppressLint("SetJavaScriptEnabled")
    private void initWebView(Context context) {
//        progressbar = new ProgressBar(context, null, android.R.attr.progressBarStyleHorizontal);
//        progressbar.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, 10, 0, 0));
//        progressbar.setBackgroundColor(Color.WHITE);
//        addView(progressbar);
        requestFocus();
        clearHistory();
        clearCache(true);
        // 璁剧疆鏀寔JavaScript鑴氭湰
        WebSettings webSettings = getSettings();
        webSettings.setJavaScriptEnabled(true);
        // 璁剧疆鍙互璁块棶鏂囦欢
        webSettings.setAllowFileAccess(true);
        // 璁剧疆鏀寔缂╂斁

		// 设置可以支持缩放  
     //   webSettings.setSupportZoom(true);  
        // 设置出现缩放工具  
     //   webSettings.setBuiltInZoomControls(true);  

        webSettings.setDatabaseEnabled(true);
//      String dir =ChApplication.getApplication().getDir("database", Context.MODE_PRIVATE).getPath();
//      webSettings.setDatabasePath(dir);
        // 浣跨敤localStorage鍒欏繀椤绘墦寮�
        webSettings.setDomStorageEnabled(true);
        webSettings.setUseWideViewPort(false);  
        webSettings.setGeolocationEnabled(true);
        setWebViewClient(client);
        setWebChromeClient(new WebChromeClient());
    }

    private WebViewClient client = new WebViewClient() {
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }

        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
          
            
        }

        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        public void onFormResubmission(WebView view, android.os.Message dontResend, android.os.Message resend) {
            resend.sendToTarget();
        }

        ;
    };

    public class WebChromeClient extends android.webkit.WebChromeClient {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
//            if (newProgress == 100) {
//                progressbar.setVisibility(GONE);
////                textView.setText(getTitle());
////                if (go_back != null && !getUrl().equals(pcurl)) {
////                    go_back.setVisibility(View.VISIBLE);
////                } else if (go_back != null && getUrl().equals(pcurl)) {
////                    go_back.setVisibility(View.GONE);
////                }
//            } else {
//                if (progressbar.getVisibility() == GONE)
//                    progressbar.setVisibility(VISIBLE);
//                progressbar.setProgress(newProgress);
//                progressbar.setSecondaryProgress(newProgress + 100);
//            }
            super.onProgressChanged(view, newProgress);
        }

        // 澶勭悊javascript涓殑alert
        @Override
        public boolean onJsAlert(WebView view, String url, String message,
                                 final JsResult result) {
            Builder builder = new Builder(getContext());
            builder.setTitle("娑堟伅");
            builder.setMessage(message);
            builder.setPositiveButton(android.R.string.ok, new AlertDialog.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    result.confirm();
                }
            });
            builder.setCancelable(false);
            builder.create();
            builder.show();
            return true;
        }

        // 澶勭悊javascript涓殑confirm
        @Override
        public boolean onJsConfirm(WebView view, String url, String message,
                                   final JsResult result) {
            Builder builder = new Builder(getContext());
            builder.setTitle("confirm");
            builder.setMessage(message);
            builder.setPositiveButton(android.R.string.ok, new AlertDialog.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    result.confirm();
                }
            });
            builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    result.cancel();
                }
            });
            builder.setCancelable(false);
            builder.create();
            builder.show();
            return true;
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            //textView.setText(title);
            //benefit.z_skip.setVisibility(View.GONE);
        }

        @SuppressWarnings("deprecation")
        @Override
        public void onExceededDatabaseQuota(String url,
                                            String databaseIdentifier, long quota,
                                            long estimatedDatabaseSize, long totalQuota,
                                            QuotaUpdater quotaUpdater) {

            super.onExceededDatabaseQuota(url, databaseIdentifier, quota,
                    estimatedDatabaseSize, totalQuota, quotaUpdater);
            quotaUpdater.updateQuota(estimatedDatabaseSize * 2);
        }

        @Override
        public void onGeolocationPermissionsShowPrompt(String origin,
                                                       Callback callback) {
            callback.invoke(origin, true, false);
            super.onGeolocationPermissionsShowPrompt(origin, callback);
        }

        @Override
        public void onReachedMaxAppCacheSize(long requiredStorage, long quota,
                                             QuotaUpdater quotaUpdater) {
            quotaUpdater.updateQuota(requiredStorage * 2);
        }
    }


    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
//        @SuppressWarnings("deprecation")
//        LayoutParams lp = (LayoutParams) progressbar.getLayoutParams();
//        lp.x = l;
//        lp.y = t;
//        lp.height = 10;
//        progressbar.setLayoutParams(lp);
        super.onScrollChanged(l, t, oldl, oldt);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((keyCode == KeyEvent.KEYCODE_BACK) && canGoBack()) {
                WebBackForwardList mWebBackForwardList = copyBackForwardList();
                if (mWebBackForwardList.getSize() == 1) {
//                    if (ActivityManager.getActivitys().containsKey("ThePreferentialBenefit")) {
//                        ActivityManager.getActivity("ThePreferentialBenefit").finish();
//                        ActivityManager.removeActivity("ThePreferentialBenefit");
//                    }

                    return true;
                }

                goBack();

                return true;
            }
        }
        return false;
    }


}
